package com.wang.avi.indicators;

import com.wang.avi.AVLoadingIndicatorView;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;

import java.util.ArrayList;

/**
 * Created by Jack on 2015/10/19.
 */
public class LineScaleIndicator extends AVLoadingIndicatorView {

    public static final float SCALE=1.0f;

    float[] scaleYFloats=new float[]{SCALE,
            SCALE,
            SCALE,
            SCALE,
            SCALE,};

    public LineScaleIndicator(Context context) {
        super(context);
        Component.DrawTask task = (component, canvas) -> {
            setPaint();
            setBound();
            draw(canvas,getPaint());
        };
        addDrawTask(task);
    }

    @Override
    public void addDrawTask(Component.DrawTask drawTask){
        super.addDrawTask(drawTask);
        drawTask.onDraw(this, mCanvasForTaskOverContent);
    }

    @Override
    public void draw(Canvas canvas, Paint paint) {
        float translateX=getWidth()/11;
        float translateY=getHeight()/2;
        for (int i = 0; i < 5; i++) {
            canvas.save();
            canvas.translate((2 + i * 2) * translateX - translateX / 2, translateY);
            canvas.scale(SCALE, scaleYFloats[i]);
            RectFloat rectF=new RectFloat(-translateX/2,-getHeight()/2.5f,translateX/2,getHeight()/2.5f);
            canvas.drawRoundRect(rectF, 5, 5, paint);
            canvas.restore();
        }
    }

    @Override
    public ArrayList<AnimatorValue> onCreateAnimators() {
        ArrayList<AnimatorValue> animators=new ArrayList<>();
        long[] delays=new long[]{100,200,300,400,500};
        for (int i = 0; i < 5; i++) {
            final int index=i;
            AnimatorValue scaleAnim=new AnimatorValue();
            scaleAnim.setDuration(1000);
            scaleAnim.setLoopedCount(-1);
            scaleAnim.setDelay(delays[i]);
            addUpdateListener(scaleAnim, new AnimatorValue.ValueUpdateListener() {
                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    if(v<0.5f)
                        scaleYFloats[index] = (float) (-1.2*v+1);
                    else
                        scaleYFloats[index] = (float) (1.2*v-0.2);
                    invalidate();
                }
            });
            animators.add(scaleAnim);
        }
        return animators;
    }

}
